import { NumUnit } from "./untis/num"


const operators = ["+", "-", "*", "/", "(", ")", " "]


function parseUnit(mode?: string) : Unit {
    switch(mode) {
        case "num":
            return new NumUnit()
        default:
            return new NumUnit()
    }
}

function unitParse(tok: string, mode?: string) : string {

    const unit = parseUnit(mode)
    try {
        return unit.parse(tok).toString()
    }catch{
        return tok
    }
}

function toUnited(num: number, mode?: string, local?: string) : string {
    const unit = parseUnit(mode)
    try {
        return unit.format(num, local)
    }catch{
        return num.toString()
    }
}


export function calcExpr(expr: string, mode?: string, local?: string) : string{

    let tokens: string[]  = [];
    let start = 0;
    for (let i = 0; i < expr.length; i++) {
        if (operators.includes(expr[i])) {
            tokens.push( unitParse(expr.substring(start, i)))
            tokens.push(expr[i])
            start = i+1
        }
    }
    tokens.push(unitParse(expr.substring(start)))


    //console.log(tokens)

    const parsedExpr = tokens.join(' ')
    try {
        let result : number = eval(parsedExpr);
        if (typeof result === 'number') {
            if (Number.isFinite(result) && !Number.isNaN(result)){
                return toUnited(result, mode, local);
            }
        }
    }catch{
    }
    return ""
}